package com.example.hotHub.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linyunjian5
 */
public class SimpleMap extends LinkedHashMap {
    public static SimpleMap build() {
        return new SimpleMap();
    }

    public static <T> T parse(String jsonStr, Class<T> clazz) {
        T value = JSONObject.parseObject(jsonStr, clazz);
        return value;
    }

    public static <T> List<T> parseArray(String jsonStr, Class<T> clazz) {
        List<T> list = JSONObject.parseArray(jsonStr, clazz);
        return list;
    }

    public  <T> T get(Object key, Class<T> clazz) {
        Object obj = super.get(key);
        if (obj == null) {
            return null;
        }
        T value = JSONObject.parseObject(JSON.toJSONString(obj), clazz);
        return (T) value;
    }

    public <T> List<T> getList(Object key, Class<T> clazz) {
        Object obj = super.get(key);
        String listJsonStr = JSONObject.parseObject(JSON.toJSONString(obj), String.class);
        List<T> list = JSONObject.parseArray(listJsonStr, clazz);
        return list;
    }

    public String getString(Object key) {
        return this.get(key, String.class);
    }

    public Integer getInt(Object key) {
        return this.get(key, Integer.class);
    }

    public Double getDouble(Object key) {
        return this.get(key, Double.class);
    }

    public Date getDate(Object key) {
        return this.get(key, Date.class);
    }

    public Long getLong(Object key) {
        return this.get(key, Long.class);
    }

    public Boolean getBoolean(Object key) {
        return this.get(key, Boolean.class);
    }

    public SimpleMap getMap(Object key) {
        return this.get(key, SimpleMap.class);
    }

    public SimpleMap put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public SimpleMap put(Boolean flag, String key, Object value) {
        if (flag) {
            super.put(key, value);
        }
        return this;
    }

    public SimpleMap putIfNotEmpty(String key, Object value) {
        if (!ObjectUtils.isEmpty(value)) {
            super.put(key, value);
        }
        return this;
    }

    public SimpleMap put(String key, Object value, Object defaultValue) {
        if (!ObjectUtils.isEmpty(value)) {
            super.put(key, value);
        } else {
            super.put(key, defaultValue);
        }
        return this;
    }

    public SimpleMap putInCondition(Boolean flag, String key, Object valueWhileTrue, Object valueWhileFalse) {
        if (flag) {
            super.put(key, valueWhileTrue);
        } else {
            super.put(key, valueWhileFalse);
        }
        return this;
    }

}
